package com.huazhi.wzsnw.controller;

import com.huazhi.wzsnw.constant.SysConstants;
import com.huazhi.wzsnw.model.Alert;
import com.huazhi.wzsnw.model.Menu;
import com.huazhi.wzsnw.model.Role;
import com.huazhi.wzsnw.model.User;
import com.huazhi.wzsnw.model.po.MenuView;
import com.huazhi.wzsnw.service.*;
import com.huazhi.wzsnw.util.Md5Util;
import com.huazhi.wzsnw.util.TreeUtil;
import com.huazhi.wzsnw.util.VerifyCodeUtil;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpCookie;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private LogService logService;
    @Autowired
    private AlertService alertService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }


    @RequestMapping(value = "/getCheckByUserNamePassword", method = RequestMethod.POST)
    public ModelAndView getCheckByUserNamePassword(Model model, HttpServletRequest request,
                                                   HttpSession httpSession) {
        try {
            String username = request.getParameter("username");
            String passwordstring = request.getParameter("password");
            User user = userService.findByField("username", username.trim());
            if (user == null) {
                return json("0");
            } else {
                if ("0".equalsIgnoreCase(user.getState())) {
                    return json("1");
                } else {
                    String password = Md5Util.encryption(passwordstring, user.getSalt());
                    User user1 = userService.getUserByTidPassword(user.getTid(), password);
                    if (user1 == null) {
                        return json("2");
                    } else {
                        return json("3");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @RequestMapping(value = "/getCheckByuserNamePasswordPhone", method = RequestMethod.POST)
    public ModelAndView getCheckByuserNamePasswordPhone(Model model, HttpServletRequest request,
                                                        HttpSession httpSession) {
        try {
            String username = request.getParameter("username");
            String passwordstring = request.getParameter("password");
            VerifyCodeUtil verifyCodeUtil = new VerifyCodeUtil();
            String odlverifyCode = null;
            Cookie[] cookies = request.getCookies();
            for (Cookie c : cookies) {
                if (c.getName().equals("VerifyCode")) {
                    odlverifyCode = c.getValue();
                }
            }
            String verifyCode = request.getParameter("verifyCode");
            User user = userService.findByField("username", username.trim());
            if (!odlverifyCode.equals(verifyCode)) {
                return json("4");
            }
            if (user == null) {
                return json("0");
            } else {
                if ("0".equalsIgnoreCase(user.getState())) {
                    return json("1");
                } else {
                    String password = Md5Util.encryption(passwordstring, user.getSalt());
                    User user1 = userService.getUserByTidPassword(user.getTid(), password);
                    if (user1 == null) {
                        return json("2");
                    } else {
                        return json("3");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @RequestMapping(value = "/login", method = {RequestMethod.POST, RequestMethod.GET})
    public String login(HttpServletRequest request,
                        HttpSession httpSession) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Subject subject = SecurityUtils.getSubject();
        //判断有没有用户登录
        if (!subject.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            //开启记住密码
            token.setRememberMe(true);
            try {
                subject.login(token);
                Session session = subject.getSession();
                session.setAttribute("user", (User) subject.getPrincipal());
                System.out.println(subject.getPrincipal());
                Alert alert = new Alert();
                alert.setIsShow(1);
                alert.setState("0");
                List<String> list = alertService.getSearchAlertList(null, alert);
                if (list.isEmpty()) {
                    session.setAttribute("buyer", "0");
                } else {
                    session.setAttribute("buyer", "1");
                }
//                logService.getAddLog("用户管理","用户登录", "登录系统");

//                Boolean aBoolean=subject.hasRole("instrument:register:buyer"); //返回一个boolean型
//                if(aBoolean){
//                    session.setAttribute("buyer", "1");
//                }else {
//                    session.setAttribute("buyer", "0");
//                }
//                System.out.println(aBoolean+"??????????????????????????");
                return "index";
            } catch (UnknownAccountException uae) {
                // UnknownAccountException账号不存在异常
                System.out.println("===============账号不存在异常=>" + token.getPrincipal());
                return "redirect:/login.jsp";
            } catch (IncorrectCredentialsException ice) {
                // IncorrectCredentialsException密码错误异常
                System.out.println("===============密码错误异常=>" + token.getPrincipal());
            } catch (LockedAccountException lae) {
                // LockedAccountException账户被锁定异常
                System.out.println("===============账户被锁定异常=>" + token.getPrincipal());
            } catch (AuthenticationException ae) {
                // AuthenticationException即验证不通过异常，为前面几个异常的父类
            }
        }
        return "redirect:/login.jsp";
    }

    @RequestMapping(value = "/phoneLogin", method = RequestMethod.GET)
    public String getPhonePage() {
        return "phoneLogin";
    }

    @RequestMapping(value = "/checkPhoneLogin", method = {RequestMethod.POST, RequestMethod.GET})
    public String Phonelogin(HttpServletRequest request,
                             HttpSession httpSession) {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Subject subject = SecurityUtils.getSubject();
        //判断有没有用户登录
        if (!subject.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            //开启记住密码
            token.setRememberMe(true);
            try {
                subject.login(token);
                Session session = subject.getSession();
                session.setAttribute("user", (User) subject.getPrincipal());
                System.out.println(subject.getPrincipal());
                Alert alert = new Alert();
                alert.setIsShow(1);
                alert.setState("0");
                List<String> list = alertService.getSearchAlertList(null, alert);
                if (list.isEmpty()) {
                    session.setAttribute("buyer", "0");
                } else {
                    session.setAttribute("buyer", "1");
                }
                logService.getAddLog("用户管理", "用户登录", "登录系统");
//                Boolean aBoolean=subject.hasRole("instrument:register:buyer"); //返回一个boolean型
//                if(aBoolean){
//                    session.setAttribute("buyer", "1");
//                }else {
//                    session.setAttribute("buyer", "0");
//                }
//                System.out.println(aBoolean+"??????????????????????????");
                return "instrument/phoneRili";
            } catch (UnknownAccountException uae) {
                // UnknownAccountException账号不存在异常
                System.out.println("===============账号不存在异常=>" + token.getPrincipal());
                return "redirect:/phoneLogin.jsp";
            } catch (IncorrectCredentialsException ice) {
                // IncorrectCredentialsException密码错误异常
                System.out.println("===============密码错误异常=>" + token.getPrincipal());
            } catch (LockedAccountException lae) {
                // LockedAccountException账户被锁定异常
                System.out.println("===============账户被锁定异常=>" + token.getPrincipal());
            } catch (AuthenticationException ae) {
                // AuthenticationException即验证不通过异常，为前面几个异常的父类
            }
        }
        return "redirect:/phoneLogin.jsp";
    }

    @RequestMapping(value = "/getVerifyCode", method = RequestMethod.GET)
    public void getVerifyCode(HttpServletRequest request, HttpSession session, HttpServletResponse response) throws FileNotFoundException, IOException {
        VerifyCodeUtil verifyCodeUtil = new VerifyCodeUtil();
        BufferedImage bufferedImage = verifyCodeUtil.getImage();
        String str = verifyCodeUtil.getText();
        Cookie cookie = new Cookie("VerifyCode", str);
        response.addCookie(cookie);
        ImageIO.write(bufferedImage, "png", response.getOutputStream());
    }


    //退出系统
    @RequestMapping(value = "/logOut", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView logOut(HttpServletRequest request,
                               HttpSession httpSession, HttpServletResponse response) {
        logService.getAddLog("用户管理", "用户登录", "退出系统");
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "退出成功");
        jsonObject.put("data", null);
        return json(jsonObject);
    }

    @RequestMapping(value = "/init", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView init(HttpServletRequest request,
                             HttpSession httpSession, HttpServletResponse response) {
        JSONObject jsonObject = new JSONObject();
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("title", "五指山农污远程监控平台");
        jsonObject1.put("href", request.getContextPath() + "/rest/getRoute?type=home&url=home");

        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("title", "五指山农污远程监控平台");
        jsonObject2.put("href", request.getContextPath() + "/rest/getRoute?type=home&url=home");

        if (user.getIssuper().equalsIgnoreCase("0") && user.getUsername().equalsIgnoreCase(SysConstants.ADMIN)) {
            List<Menu> menuList = menuService.findAll();
            List<MenuView> menuInfo = new ArrayList<>();
            for (Menu e : menuList) {
                if (!"3".equalsIgnoreCase(e.getType())) {
                    MenuView menuVO = new MenuView();
                    menuVO.setTid(e.getTid());
                    menuVO.setParentTid(e.getParentTid());
                    menuVO.setHref(e.getHref());
                    menuVO.setTitle(e.getTitle());
                    menuVO.setIcon(e.getIcon());
                    menuVO.setTarget(e.getTarget());
                    menuInfo.add(menuVO);
                }
            }
            jsonObject.put("menuInfo", TreeUtil.toTree(menuInfo, "0"));
        } else {
            List<Role> roles = roleService.getRolesByUserTid(user.getTid());
            if (roles.size() != 0) {
                for (Role role : roles) {
                    List<String> roleMenus = roleMenuService.getMenuTidByRoleTid(role.getTid());
                    if (roleMenus.size() != 0) {
                        List<Menu> menuList = menuService.findAll();
                        List<MenuView> menuInfo = new ArrayList<>();
                        for (Menu e : menuList) {
                            if (!"3".equalsIgnoreCase(e.getType())) {
                                boolean flag = roleMenus.contains(e.getTid());
                                if (flag) {
                                    MenuView menuVO = new MenuView();
                                    menuVO.setTid(e.getTid());
                                    menuVO.setParentTid(e.getParentTid());
                                    menuVO.setHref(e.getHref());
                                    menuVO.setTitle(e.getTitle());
                                    menuVO.setIcon(e.getIcon());
                                    menuVO.setTarget(e.getTarget());
                                    menuInfo.add(menuVO);
                                }
                            }
                        }
                        jsonObject.put("menuInfo", TreeUtil.toTree(menuInfo, "0"));
                    }
                }
            }
        }
        jsonObject.put("homeInfo", jsonObject1);
        jsonObject.put("logoInfo", jsonObject2);
        return json(jsonObject);
    }

    @RequestMapping(value = "/clear", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView clear(HttpServletRequest request,
                              HttpSession httpSession, HttpServletResponse response) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 1);
        jsonObject.put("msg", "清除服务端缓存成功");
        return json(jsonObject);
    }
    private ModelAndView json(Object result) {
        return new ModelAndView("jsonView").addObject("result", result);
    }


}

